<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\logic\GoodsPromFactory;

/**
 * 商品接口
 */
class Goods extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $model = null;
    protected $limitFields = '';

    public $type;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('common/Goods');
        $this->type = \app\common\model\Goods::getType();

    }

    public function index()
    {
        $price_range = $this->request->request('price','0');
        $this->limitFields = 'id,name,image,shop_price,exchange_integral,sales_sum';
        $this->searchFields = 'name';
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();
        $goods_where = ' exchange_integral < shop_price ';

        //价格区间
        $price_where = [];
        switch ($price_range){

            case 1:
                $price_where['shop_price'] = ['between','0,50'];
                break;
            case 2:
                $price_where['shop_price'] = ['between','50,200'];

                break;
            case 3:
                $price_where['shop_price'] = ['between','200,1000'];

                break;
            case 4:
                $price_where['shop_price'] = ['between','1000,3000'];

                break;
            case 5:
                $price_where['shop_price'] = ['between','3000,10000'];

                break;
            default:
                $price_where['shop_price'] = ['between','0,100000'];
        }
        $total = $this->model
            ->where($where)
            ->where(function ($query) use ($goods_where,$price_where) {
                $query->where('status', 1);
                $query->where('prom_type', 0);
                $query->where($goods_where);
                $query->where($price_where);
            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->field($field)
            ->where($where)
            ->where(function ($query) use ($goods_where,$price_where) {
                $query->where('status', 1);
                $query->where('prom_type', 0);
                $query->where($goods_where);
                $query->where($price_where);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

//        dump($this->model->getLastSql());exit;



        foreach ($list as $k => $v) {
            $cartNum = Db::name('cart')->where(['goods_id' => $v['id'],'user_id' => $this->auth->id])->value('goods_num');

            if ($cartNum) {
                $list[$k]['cartNum'] = $cartNum;
            } else {
                $list[$k]['cartNum'] = 0;
            }

        }

        $result = array("total" => $total, "rows" => $list);
        $this->success('', $result);
    }

    /**
     * 详情
     */
    public function detail($ids = NULL)
    {
        \app\common\model\Goods::addzuji($ids, $this->auth->id);
        $this->limitFields = 'id,name,image,images,market_price,shop_price,exchange_integral,content';
        $row = \app\common\model\Goods::get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $goodsAttrData = Db::name('goods_attr')->alias('ga')
            ->join('attr a', 'ga.attr_id = a.id', 'LEFT')
            ->where(['goods_id' => $ids])
            ->field('a.name')
            ->find();
        $row['attrName'] = $goodsAttrData['name'];

        $goodsAttrM = model('common/goodsAttr');
        $goodsAttr = $goodsAttrM->field('id,attr_value')->where(['goods_id' => $ids])->select();

        $row['goodsAttr'] = $goodsAttr;
        $row['type'] = $this->type;


        if ($row->prom_type == 2) {
            $row['type'] = [
                ['id' => '0', 'name' => '自己买'],
                ['id' => '1', 'name' => '送一人']
            ];
        }

        $goodsPromFactory = new GoodsPromFactory();
        if (!empty($row['prom_id']) && $goodsPromFactory->checkPromType($row['prom_type'])) {
            $goodsPromLogic = $goodsPromFactory->makeModule($row);//这里会自动更新商品活动状态，所以商品需要重新查询
            $row = $goodsPromLogic->getGoodsInfo();//上面更新商品信息后需要查询
//            dump($goodsPromLogic);exit;
            $ActivityGoodsInfo = $goodsPromLogic->getActivityGoodsInfo();

//            dump($ActivityGoodsInfo->toArray());exit;
            if (isset($ActivityGoodsInfo['item_id']) && $ActivityGoodsInfo['item_id']) {
                $ActivityGoodsInfo['goodsAttr'] = $goodsAttrM->field(['id,attr_value'])->where(['id' => $ActivityGoodsInfo['item_id']])->select();
            }

            $row = $ActivityGoodsInfo;
        }

        $this->success('', $row);
    }


    /**
     * 下单页面
     * $goods_id 商品id
     * $goods_attr_id 商品规格表id
     * $type 购买类型
     */
    public function order()
    {
        $goods_id = $this->request->request('goods_id');
        $goods_attr_id = $this->request->request('goods_attr_id');
        $type = $this->request->request('type');
        $num = $this->request->request('num/d');
        $userPromId = $this->request->request('user_prom_id');
        $isAlone = $this->request->request('is_alone/d', 0);

//        $goods = Db::name('goods')->where(['id' => $goods_id])->field('id,name,image,market_price,shop_price,exchange_integral,prom_type,prom_id')->find();

        $goods = $this->model->get($goods_id);

        $goodsPromFactory = new \app\common\logic\GoodsPromFactory();
        if (!empty($goods['prom_id']) && $goodsPromFactory->checkPromType($goods['prom_type'])) {
            $goodsPromLogic = $goodsPromFactory->makeModule($goods);//这里会自动更新商品活动状态，所以商品需要重新查询
            $goods = $goodsPromLogic->getGoodsInfo();//上面更新商品信息后需要查询

            $ActivityGoodsInfo = $goodsPromLogic->getActivityGoodsInfo();
            $goodsAttrM = new \app\common\model\GoodsAttr();

            if (isset($ActivityGoodsInfo['item_id']) && $ActivityGoodsInfo['item_id']) {
                $ActivityGoodsInfo['goodsAttr'] = $goodsAttrM->field(['id,attr_value'])->where(['id' => $ActivityGoodsInfo['item_id']])->select();
            }

            if ($ActivityGoodsInfo['prom_type'] == '3') {
                //秒杀
                $ActivityGoodsInfo['shengyu_count'] = $ActivityGoodsInfo['goods_num'] - $ActivityGoodsInfo['buy_num'];
            } elseif ($ActivityGoodsInfo['prom_type'] == '1') {
                //砍价
                $deal_price = Db::name('cutdown_follow')->where(['id' => $userPromId])->value('deal_price');
                $ActivityGoodsInfo['shop_price'] = $deal_price; //最终成交价格
            } elseif ($ActivityGoodsInfo['prom_type'] == '2') {
                //拼团
                if ($isAlone == 1) {
                    //拼团商品单独购买
                    $ActivityGoodsInfo['shop_price'] = $ActivityGoodsInfo['old_shop_price'];
                }
            }


            $goods = $ActivityGoodsInfo;

        }

        $goods['num'] = $num;
        $goods['attr_value'] = Db::name('goods_attr')->where(['id' => $goods_attr_id])->value('attr_value');
        $goods['item_id'] = $goods_attr_id;
        $goods['user_prom_id'] = $userPromId;

        $goodsAttrData = Db::name('goods_attr')->alias('ga')
            ->join('attr a', 'ga.attr_id = a.id', 'LEFT')
            ->where(['goods_id' => $goods_id])
            ->field('a.name')
            ->find();
        $goods['attrName'] = $goodsAttrData['name'];

        //用户积分不足
        $score = Db::name('user')->where(['id' => $this->auth->id])->value('score');
        if ($score - $goods['exchange_integral'] < 0) {
            $goods['exchange_integral'] = 0;
        }

        $this->success('', $goods);

    }


    public function test()
    {
        $goodsPromFactory = new GoodsPromFactory();

        $goods_id = input("get.id/d", 0);
        $Goods = new \app\common\model\Goods();
        $goods = $Goods::get($goods_id);

        if (!empty($goods['prom_id']) && $goodsPromFactory->checkPromType($goods['prom_type'])) {
            $goodsPromLogic = $goodsPromFactory->makeModule($goods);//这里会自动更新商品活动状态，所以商品需要重新查询
            $goods = $goodsPromLogic->getGoodsInfo();//上面更新商品信息后需要查询

        }
        dump($goods->toArray());
    }


    /**
     * 积分兑换
     */
    public function integralMall()
    {

        $score = Db::name('user')->where('id', $this->auth->id)->value('score');


        $brandType = $this->request->request('brandType');
        $default_where = function ($query) {
            $query->where('status', '1');
            $query->where('exchange_integral', '>', '1');
            $query->where('prom_type', '0');
        };

        $goods_where = ' status = "1" and exchange_integral > 0 ';

        //积分+金额
        if ($brandType == 1) {
            $goods_where .= '  and exchange_integral < shop_price ';
        } else {
            $goods_where .= '  and exchange_integral = shop_price ';
        }


        $this->limitFields = 'id,name,image,shop_price,exchange_integral';
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where(function ($query) use ($goods_where, $default_where) {
//                $query->where($default_where);
                $query->where($goods_where);

            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->field($field)
            ->where($where)
            ->where(function ($query) use ($goods_where) {
//                $query->where($default_where);
                $query->where($goods_where);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

//        return $this->model->getLastSql();
        $result = array("total" => $total, "rows" => $list);
        $this->success('', ['score' => $score, 'list' => $result]);

    }


    /**
     * 我的足迹
     */
    public function myzuji()
    {
        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        $key = "viewHistory-" . $this->auth->id;

        $goodsIds = $client->lrange($key, 0, -1);

        $goodsList = [];
        if (!empty($goodsIds)) {

            foreach ($goodsIds as $k => $v) {
                $goods = Db::name('goods')->field('id,name,image,shop_price,exchange_integral,prom_type,prom_id')->find($v);
                array_push($goodsList, $goods);
            }
        }

        $this->success('', $goodsList);
    }

    /**
     * 足迹
     */
    public function delzuji()
    {
        $ids = $this->request->request('ids');
        $arr = explode(',', $ids);

        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        $key = "viewHistory-" . $this->auth->id;

        foreach ($arr as $k => $v) {
            $res = $client->lrem($key, 1, $v);
        }

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 最近搜索
     */
    public function lastSearchList()
    {

        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        $key = "lastSearch-" . $this->auth->id;
        $list = $client->lrange($key, 0, -1);
        $this->success('', $list);

    }

    /**
     * 添加最近搜索
     */
    public function addLastSearch()
    {
        $keywords = $this->request->get('keywords');
//        $this->success('',$keywords);
        $keywords = urldecode($keywords);

        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        $key = "lastSearch-" . $this->auth->id;
        $client->lrem($key, 1, $keywords); //如果已存在删除之前的
        if ($client->llen($key) > 12) {
            $client->rpop($key);
        }
        $client->lpush($key, $keywords);
    }

    /**
     * 删除最近搜索
     */
    public function delLastSearch()
    {
        $config = \think\Config::get('redis');
        $client = new \Predis\Client($config);
        $key = "lastSearch-" . $this->auth->id;
        $client->ltrim($key, 1, 0);
    }

}